import Koa from 'koa';
import Router from 'koa-router';
import BodyParser from 'koa-bodyparser';
import cors from 'koa2-cors';
import jwt from 'koa-jwt';
import mongoose from 'mongoose';

import UserControl from './server/users';
import ArticleControl from './server/article';
import SayControl from './server/say';
import CommentControl from './server/comment';
import oauth from './server/oauth';
import { PORT, DEV, SECRET } from './config';
import error from './middlewares/error_back';

const app = new Koa();
const router = new Router();

const port = process.env.NODE_ENV === 'production' ? 3101 : PORT;

const db = mongoose.createConnection('mongodb://react:lol970568830@localhost:27000/react', {
  useMongoClient: true,
});
mongoose.set('debug', DEV);
mongoose.Promise = global.Promise;

db.on('error', console.error.bind(console, 'connect error: '));
db.once('open', () => {
  console.log('connected@!');
});

app.use(cors());
app.use(error);
app.use(jwt({ secret: SECRET }).unless({
  path: [
    /^\/public/,
    /^\/oauth/,
    /^\/article\/list/,
    /^\/article\/detail/,
    /^\/say\/list/,
    /^\/say\/detail/,
  ],
}));
// app.use(authVerify);
app.use(BodyParser({ enableTypes: ['json', 'form', 'text'] }));

router
  .use('/oauth', oauth.routes())
  .get('/', UserControl.login)
  .post('/register', UserControl.register)
  .post('/user/getUserInfo', UserControl.getUserInfo)
  .post('/test', UserControl.register)
  .post('/article/new', ArticleControl.new)
  .post('/article/list', ArticleControl.list)
  .post('/article/detail', ArticleControl.detail)
  .post('/comment/create', CommentControl.create)
  .post('/comment/list', CommentControl.list)
  .post('/comment/detail', CommentControl.detail)
  .post('/say/create', SayControl.create)
  .post('/say/list', SayControl.list)
  .post('/say/detail', SayControl.detail);

app.use(router.routes());

app.listen(port, () => {
  console.log(`localhost: ${port}`);
});
